//
//  ImagePickerView.swift
//  FaceVerify
//
//  Created by duzexu on 2017/3/3.
//  Copyright © 2017年 duzexu. All rights reserved.
//

import UIKit
import PKHUD

@objc public protocol ImagePickerViewDelegate {
    func didSelectWithImage(imageView:ImagePickerView,image: UIImage)
}

public class ImagePickerView: UIImageView {
    
    @IBOutlet var delegate:ImagePickerViewDelegate?
    
    var vaild: Bool {
        get {
            return imagePath != nil && isLoading == false;
        }
    }
    
    var imagePath: String?
    var isLoading: Bool = false {
        willSet {
            if newValue {
                HUD.show(.systemActivity, onView: self)
            }else{
                HUD.flash(.success, onView: self)
            }
        }
    }
    
    override public func awakeFromNib() {
        super.awakeFromNib()
        self.setupView()
    }
    
    func setupView() -> Void {
        let tap = UITapGestureRecognizer(target: self, action: #selector(imageTaped(view:)))
        self.isUserInteractionEnabled = true
        self.addGestureRecognizer(tap)
    }
    
}

extension ImagePickerView: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    func imageTaped(view: UIView) -> Void {
        let picker = UIImagePickerController()
        picker.delegate = self
        picker.sourceType = .photoLibrary
        if let vc = self.delegate as? UIViewController {
            vc.present(picker, animated: true, completion: nil)
        }
    }
    
    public func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
    
    public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        let path = info[UIImagePickerControllerReferenceURL] as! NSURL
        self.image = image
        self.imagePath = path.absoluteString
        self.delegate?.didSelectWithImage(imageView: self, image: image)
        picker.dismiss(animated: true, completion: nil)
    }
    
}
